package com.gisterrier.client.components;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.TreeMap;

import com.common.shared.ClSelectionItem;
import com.gisterrier.client.GisTerrier;
import com.gisterrier.shared.ClSelection;
import com.gisterrier.shared.Customer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.util.BooleanCallback;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.DateItem;
import com.smartgwt.client.widgets.form.fields.IntegerItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;

public class PBillingCustSearch extends VLayout {

	private SelectItem siRegion;
	private SelectItem siSubRegion;
	private SelectItem siCity;
	private SelectItem siStreet;

	private IntegerItem tiCustomerNum;
	private TextItem tiCustomerName;
	private TextItem tiPersonalNum;
	private TextItem tiBankIdentCode;

	private SelectItem siBuildingType;
	private TextItem tiBuildingNum;
	private TextItem tiFlat;
	private TextItem tiPhone;
	private TextItem tiDocumentNum;
	private DateItem diDate;

	private SelectItem siCusBuisness;
	private TextItem tiWorkPlace;
	private SelectItem siCusType;
	private SelectItem siCusState;
	private SelectItem siTarifPlan;
	private SelectItem siCustScope;
	private SelectItem siGivenPressure;
	private SelectItem siCustlogType;

	private boolean settingMyself = false;

	private TextItem tiUser;

	public PBillingCustSearch() {
		super();
		setHeight100();
		setWidth100();
		this.setMembersMargin(10);
		DynamicForm form = new DynamicForm();

		form.setWidth100();
		// form.setBorder("1px solid red");
		form.setTitleAlign(Alignment.LEFT);

		siRegion = new SelectItem();
		siRegion.setTitle("Region");
		siRegion.setWidth("100%");

		siSubRegion = new SelectItem();
		siSubRegion.setTitle("Sub Region");
		siSubRegion.setWrapTitle(false);
		siSubRegion.setWidth("100%");

		siCity = new SelectItem();
		siCity.setTitle("City");
		siCity.setWidth(200);
		siCity.setWidth("100%");

		siStreet = new SelectItem();
		siStreet.setTitle("Street");
		siStreet.setWidth("100%");

		tiCustomerNum = new IntegerItem();
		tiCustomerNum.setTitle("Customer Num");
		tiCustomerNum.setWrapTitle(false);
		tiCustomerNum.setWidth("100%");

		tiCustomerName = new TextItem();
		tiCustomerName.setTitle("Customer Name");
		tiCustomerName.setWrapTitle(false);
		tiCustomerName.setWidth("100%");

		tiPersonalNum = new TextItem();
		tiPersonalNum.setTitle("Personal Num");
		tiPersonalNum.setWrapTitle(false);
		tiPersonalNum.setWidth("100%");

		tiBankIdentCode = new TextItem();
		tiBankIdentCode.setTitle("Bank Iden. Code");
		tiBankIdentCode.setWrapTitle(false);
		tiBankIdentCode.setWidth("100%");

		siBuildingType = new SelectItem();
		siBuildingType.setTitle("Build.type");
		siBuildingType.setWidth("100%");

		tiBuildingNum = new TextItem();
		tiBuildingNum.setTitle("Building Num");
		tiBuildingNum.setWrapTitle(false);
		tiBuildingNum.setWidth("100%");

		tiFlat = new TextItem();
		tiFlat.setTitle("Flat");
		tiFlat.setWrapTitle(false);
		tiFlat.setWidth("100%");

		tiPhone = new TextItem();
		tiPhone.setTitle("Phone");
		tiPhone.setWrapTitle(false);
		tiPhone.setWidth("100%");

		tiDocumentNum = new TextItem();
		tiDocumentNum.setTitle("Document Num");
		tiDocumentNum.setWrapTitle(false);
		tiDocumentNum.setWidth("100%");

		diDate = new DateItem();
		diDate.setTitle("Date");
		diDate.setWrapTitle(false);
		diDate.setWidth("100%");

		siCusBuisness = new SelectItem();
		siCusBuisness.setTitle("Cust. Buisness");
		siCusBuisness.setWrapTitle(false);
		siCusBuisness.setWidth("100%");

		tiWorkPlace = new TextItem();
		tiWorkPlace.setTitle("Working Place");
		tiWorkPlace.setWrapTitle(false);
		tiWorkPlace.setWidth("100%");

		siCusType = new SelectItem();
		siCusType.setTitle("Cust Type");
		siCusType.setWrapTitle(false);
		siCusType.setWidth("100%");

		siCusState = new SelectItem();
		siCusState.setTitle("Cust. State");
		siCusState.setWrapTitle(false);
		siCusState.setWidth("100%");

		siTarifPlan = new SelectItem();
		siTarifPlan.setTitle("Tarif Plan");
		siTarifPlan.setWrapTitle(false);
		siTarifPlan.setWidth("100%");

		siCustScope = new SelectItem();
		siCustScope.setTitle("Budjet/Non Budjet");
		siCustScope.setWrapTitle(false);
		siCustScope.setWidth("100%");

		siGivenPressure = new SelectItem();
		siGivenPressure.setTitle("Given Pressure");
		siGivenPressure.setWrapTitle(false);
		siGivenPressure.setWidth("100%");

		siCustlogType = new SelectItem();
		siCustlogType.setTitle("Operation");
		siCustlogType.setWrapTitle(false);
		siCustlogType.setWidth("100%");

		tiUser = new TextItem();
		tiUser.setTitle("User");
		tiUser.setWrapTitle(false);
		tiUser.setWidth("100%");

		form.setLayoutAlign(Alignment.LEFT);
		form.setFields(siRegion, siSubRegion, siCity, siStreet, tiCustomerNum,
				tiCustomerName, tiPersonalNum, tiBankIdentCode, siBuildingType,
				tiBuildingNum, tiFlat, tiPhone, tiDocumentNum, diDate,
				siCusBuisness, tiWorkPlace, siCusType, siCusState, siTarifPlan,
				siCustScope, siGivenPressure, siCustlogType, tiUser);

		this.addMember(form);
		final LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("-1", "--");
		siSubRegion.setValueMap(map);
		siSubRegion.setValue("-1");
		siCity.setValueMap(map);
		siCity.setValue("-1");
		siStreet.setValueMap(map);
		siStreet.setValue("-1");

		GisTerrier.gissTerrierService
				.getAllTopTypes(new AsyncCallback<TreeMap<Integer, ArrayList<ClSelectionItem>>>() {

					@Override
					public void onSuccess(
							TreeMap<Integer, ArrayList<ClSelectionItem>> result) {
						setSelectItems(siRegion,
								result.get(ClSelection.T_REGION));
						setSelectItems(siBuildingType,
								result.get(ClSelection.T_BUILDING_TYPE));
						setSelectItems(siCusBuisness,
								result.get(ClSelection.T_CUST_BUISNESS));
						setSelectItems(siCusType,
								result.get(ClSelection.T_CUST_TYPE));
						setSelectItems(siCusState,
								result.get(ClSelection.T_CUST_STATUS));
						setSelectItems(siTarifPlan,
								result.get(ClSelection.T_TARIF_PLAN));
						setSelectItems(siCustScope,
								result.get(ClSelection.T_CUST_SCOPE));
						setSelectItems(siGivenPressure,
								result.get(ClSelection.T_GAS_PRESS));
						setSelectItems(siCustlogType,
								result.get(ClSelection.T_CUST_LOG_TYPE));

					}

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}
				});
		siRegion.addChangedHandler(new ChangedHandler() {
			@Override
			public void onChanged(ChangedEvent event) {
				if (settingMyself)
					return;
				siSubRegion.setValueMap(map);
				siSubRegion.setValue("-1");
				siCity.setValueMap(map);
				siCity.setValue("-1");
				siStreet.setValueMap(map);
				siStreet.setValue("-1");
				long val = Long.parseLong(event.getValue().toString());
				if (val < 0)
					return;
				GisTerrier.gissTerrierService.getSubRegions(val,
						new AsyncCallback<ArrayList<ClSelectionItem>>() {

							@Override
							public void onSuccess(
									ArrayList<ClSelectionItem> result) {
								setSelectItems(siSubRegion, result);

							}

							@Override
							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub

							}
						});

			}
		});
		siSubRegion.addChangedHandler(new ChangedHandler() {
			@Override
			public void onChanged(ChangedEvent event) {
				if (settingMyself)
					return;
				siCity.setValueMap(map);
				siCity.setValue("-1");
				siStreet.setValueMap(map);
				siStreet.setValue("-1");
				long val = Long.parseLong(event.getValue().toString());
				if (val < 0)
					return;
				GisTerrier.gissTerrierService.getCities(val,
						new AsyncCallback<ArrayList<ClSelectionItem>>() {

							@Override
							public void onSuccess(
									ArrayList<ClSelectionItem> result) {
								setSelectItems(siCity, result);

							}

							@Override
							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub

							}
						});

			}
		});
		siCity.addChangedHandler(new ChangedHandler() {
			@Override
			public void onChanged(ChangedEvent event) {
				if (settingMyself)
					return;
				siStreet.setValueMap(map);
				siStreet.setValue("-1");
				long val = Long.parseLong(event.getValue().toString());
				if (val < 0)
					return;
				GisTerrier.gissTerrierService.getStreets(val,
						new AsyncCallback<ArrayList<ClSelectionItem>>() {

							@Override
							public void onSuccess(
									ArrayList<ClSelectionItem> result) {
								setSelectItems(siStreet, result);

							}

							@Override
							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub

							}
						});

			}
		});

		HLayout dynamicForm = new HLayout();
		dynamicForm.setAlign(Alignment.CENTER);
		dynamicForm.setMembersMargin(10);
		Button bSearch = new Button("Search");
		bSearch.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				searchCustomer();

			}
		});

		Button bApplyToMap = new Button("Apply to Build");

		dynamicForm.addMember(bSearch);
		dynamicForm.addMember(bApplyToMap);
		dynamicForm.setAutoHeight();
		this.addMember(dynamicForm);

		dynamicForm = new HLayout();
		dynamicForm.setAlign(Alignment.CENTER);
		dynamicForm.setMembersMargin(10);
		Button bApplyToNetwork = new Button("Apply to Network");
		dynamicForm.addMember(bApplyToNetwork);
		dynamicForm.setAutoHeight();
		this.addMember(dynamicForm);
		
	}

	private void searchCustomer() {
		// 121028
		Object obj = tiCustomerNum.getValue();
		Integer val = null;
		try {
			val = Integer.parseInt(obj.toString());
		} catch (Exception e) {
			// TODO: handle exception
		}
		if (val == null || val.intValue() < 0) {
			SC.warn("Please enter customer", new BooleanCallback() {

				@Override
				public void execute(Boolean value) {
					tiCustomerNum.focusInItem();

				}
			});
			return;
		}
		GisTerrier.gissTerrierService.getCustomer(val.intValue(),
				new AsyncCallback<Customer>() {

					@Override
					public void onSuccess(Customer result) {
						setCustomer(result);

					}

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}
				});

	}

	private void setCustomer(Customer result) {
		try {

			siRegion.setValue(-1 + "");
			final LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
			map.put("-1", "--");
			siSubRegion.setValueMap(map);
			siSubRegion.setValue("-1");
			siCity.setValueMap(map);
			siCity.setValue("-1");
			siStreet.setValueMap(map);
			siStreet.setValue("-1");
			tiCustomerName.setValue("");
			tiPersonalNum.setValue("");
			tiBankIdentCode.setValue("");
			siBuildingType.setValue(-1);
			tiBuildingNum.setValue("");
			tiFlat.setValue("");
			tiPhone.setValue("");
			tiDocumentNum.setValue("");
			diDate.setValue((Date) null);
			siCusBuisness.setValue(-1 + "");
			tiWorkPlace.setValue("");
			siCusType.setValue(-1 + "");
			siCusState.setValue(-1 + "");
			// siTarifPlan.setValue(result.get)
			siCustScope.setValue(-1 + "");
			siGivenPressure.setValue(-1 + "");
			// siCustlogType.setValue(result.get + "");
			tiUser.setValue("");

			if (result == null)
				return;
			settingMyself = true;
			siRegion.setValue(result.getRegionId() + "");
			setSelectItems(siSubRegion, result.getSubregions());
			siSubRegion.setValue(result.getSubregionId() + "");
			setSelectItems(siCity, result.getCities());
			siCity.setValue(result.getCityId() + "");
			setSelectItems(siStreet, result.getStreets());
			siStreet.setValue(result.getStreetid() + "");
			tiCustomerName.setValue(result.getCusname());
			tiPersonalNum.setValue(result.getPrivate_number());
			tiBankIdentCode.setValue(result.getCus_inn());
			siBuildingType.setValue(result.getHometypeid());
			tiBuildingNum.setValue(result.getHome());
			tiFlat.setValue(result.getFlat());
			tiPhone.setValue(result.getPhone());
			tiDocumentNum.setValue(result.getNdoc());
			diDate.setValue(new Date(result.getStartdate().getTime()));
			siCusBuisness.setValue(result.getBusiness_id() + "");
			tiWorkPlace.setValue(result.getJob());
			siCusType.setValue(result.getCustypeid() + "");
			siCusState.setValue(result.getCusstatusid() + "");
			// siTarifPlan.setValue(result.get)
			siCustScope.setValue(result.getScope_id() + "");
			siGivenPressure.setValue(result.getGasspressid() + "");
			// siCustlogType.setValue(result.get + "");
			tiUser.setValue(result.getUserr());
			MainPanel.mainPanel.zoomToBuilding(result.getBuilding_id());

		} finally {
			settingMyself = false;
		}
	}

	private void setSelectItems(SelectItem si, ArrayList<ClSelectionItem> items) {
		if (items == null) {
			items = new ArrayList<ClSelectionItem>();
		}
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("-1", "--");
		for (ClSelectionItem item : items) {
			map.put(item.getId() + "", item.getValue());
		}
		si.setValueMap(map);
		si.setValue("-1");

	}
}
